package portal.web.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import portal.excepciones.EliminarObjetoException;
import portal.facade.PortalComprasFacadeStateful;
import portal.vo.ItemVO;

@SuppressWarnings("serial")
public class EliminarEnUnoDeCarritoServlet extends HttpServlet {

	private static Logger logger = Logger.getLogger(EliminarEnUnoDeCarritoServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		processRequest(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		processRequest(req, resp);
	}

	private void processRequest(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>EliminarEnUnoDeCarritoServlet<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
		HttpSession session = req.getSession(true);
		PortalComprasFacadeStateful facadeStateful = (PortalComprasFacadeStateful) session.getAttribute("facadeStateful");
		ItemVO item = null;
		
		Long idProducto = Long.parseLong((String)req.getParameter("id"));
		item = facadeStateful.buscarItem(idProducto);
		
		if(item != null){ //el item existe en el carrito
			if (item.getCantidad() == 1) { //si hay un solo producto, elimino el item del carrito
				try {
					facadeStateful.eliminarItem(idProducto);
					
				} catch (EliminarObjetoException e) {
					logger.warn(e.getMessage());
					req.getRequestDispatcher("/jsp/error.jsp").forward(req, resp);
					
					e.printStackTrace();
				}
			} else { //hay mas de un mismo producto en el carrito
				facadeStateful.actualizarCantidadItem(idProducto, -1);
			}
			req.setAttribute("listaCarrito", facadeStateful.getListaItems());
			req.getRequestDispatcher("/jsp/carritoCompras.jsp").forward(req, resp);
			
		} else { // el item no existe en el carrito
			logger.warn("El item no existe en el carrito.");
			req.getRequestDispatcher("/jsp/error.jsp").forward(req, resp);
			
		}
		

		

	}
}
